﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;
namespace WebForm
{
    public partial class UploadAndCut : System.Web.UI.Page
    {
        protected int _sizeWidth = 150;
        protected int _sizeHeight = 100;
        protected string _defaultPath = "/Update/";
        protected string _privateFolder = string.Empty;

        //todo df 加入对flash插件是否安装的提示
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //if ((Session["BusinessAdmin"] == null) && (Session["Admin"] == null))
                //{
                //    Response.Redirect("~/Error.aspx");
                //}

                if (string.IsNullOrEmpty(Request.QueryString["newWidth"]) || string.IsNullOrEmpty(Request.QueryString["newHeight"]))
                {
                    _sizeHeight = 150;
                    _sizeWidth = 100;
                }
                else
                {
                    _sizeWidth = int.Parse(Request.QueryString["newWidth"]);
                    _sizeHeight = int.Parse(Request.QueryString["newHeight"]);
                }
                string picName = string.Empty;
                string picPath = string.Empty; //图片的完整位置和文件名称
                string picShowPath = string.Empty;////图片的完整位置和文件名称(包含随机数）

                //获取上传文件目录
                if (string.IsNullOrEmpty(Request.QueryString["folder"]))
                {
                    imgFilePath.Value = "/Update/";
                }
                else
                {
                    imgFilePath.Value = "/" + Request.QueryString["folder"] + "/";
                }

                //获取上传文件子目录
                if (string.IsNullOrEmpty(Request.QueryString["privateFolder"]))
                {
                    hfdPrivateFolder.Value = string.Empty;
                }
                else
                {
                    hfdPrivateFolder.Value = Request.QueryString["privateFolder"] + "/";
                }

                if (string.IsNullOrEmpty(Request.QueryString["picName"]))
                {
                    picName = "cutDemo.jpg";
                    imgFileName.Value = picName;
                    picPath = "/Update/" + picName;
                    picShowPath = "/Update/" + picName + "?" + DateTime.Now.Millisecond.ToString(); //加入随机数，用于强制刷新图片，以便于图片重新从服务器上获取
                }
                else
                {
                    picName = Request.QueryString["picName"];
                    //剔除文件目录名等
                    picName =Common.FileHelper.GetFileTrueName(picName);
                    imgFileName.Value = picName;
                    picPath = imgFilePath.Value + hfdPrivateFolder.Value + picName;
                    picShowPath = imgFilePath.Value + hfdPrivateFolder.Value + picName + "?" + DateTime.Now.Millisecond.ToString(); //加入随机数，用于强制刷新图片，以便于图片重新从服务器上获取
                }

                //处理图片找不到的问题，如果找不到图片就用默认图片
                if (System.IO.File.Exists(Server.MapPath(picPath)))
                {
                    //存在文件 
                }
                else
                {
                    picShowPath = "/Update/cutDemo.jpg?" + DateTime.Now.Millisecond.ToString(); //加入随机数，用于强制刷新图片，以便于图片重新从服务器上获取
                }

                target.ImageUrl = picShowPath;
            }
        }

        protected void saveImg(object sender, EventArgs e)
        {
            if (IsPostBack)
            {

                //如果是演示图片就不用保存了

                if (imgFileName.Value.ToLower() == "cutdemo.jpg")
                {
                    //注意：如果调用前台的js函数时，一定要将js函数放在html的head中或用其它办法保证要调用的方法已注册
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择要上传的图片！');</script>");//调用前台的JS函数;
                    return;
                }

                //  string[] urls = target.ImageUrl.Split('/');
                //  string _url = urls.Last();

                string _url = imgFilePath.Value + hfdPrivateFolder.Value + imgFileName.Value;

                string tempurl = Server.MapPath(_url);
                int startX = 0;
                int startY = 0;
                int width = 0;
                int height = 0;
                try
                {
                    startX = (int)double.Parse(x1.Value);
                    startY = (int)double.Parse(y1.Value);
                    width = (int)double.Parse(Iwidth.Value);
                    height = (int)double.Parse(Iheight.Value);
                }
                catch
                {
                    //注意：如果调用前台的js函数时，一定要将js函数放在html的head中或用其它办法保证要调用的方法已注册
                    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>returnValue('" + Request.QueryString["returnControlId"] + "','" + imgFilePath.Value + hfdPrivateFolder.Value + imgFileName.Value + "');</script>");//调用前台的JS函数;
                    return;

                }

                string newFileName = _url;

                //如果是修改图就创建新图，如果不创建新图会导致确定后原图被修改
                if (!string.IsNullOrEmpty(Request.QueryString["picName"]))
                {
                    string picName = Request.QueryString["picName"];
                    newFileName = GetFileTrueName(picName);//获取没有路径和随机参数的文件名
                    newFileName = DateTime.Now.ToString("yyMMddHHmmssffff") + GetExtensionName(newFileName, true);

                }
                string newUrl = Path.Combine(Server.MapPath(imgFilePath.Value + hfdPrivateFolder.Value), newFileName);

                ImgReduceCutOut(startX, startY, width, height, tempurl, newUrl);

                //注意：如果调用前台的js函数时，一定要将js函数放在html的head中或用其它办法保证要调用的方法已注册
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>returnValue('" + Request.QueryString["returnControlId"] + "','" + imgFilePath.Value + hfdPrivateFolder.Value + newFileName + "');</script>");//调用前台的JS函数;

                ////关闭本窗口
                //ClientScript.RegisterStartupScript(this.GetType(), "", "<script>closeBox();</script>");//调用前台的JS函数;

            }
        }



        /// <summary>
        /// 缩小裁剪图片
        /// </summary>
        /// <param name="int_Width">要缩小裁剪图片宽度</param>
        /// <param name="int_Height">要缩小裁剪图片长度</param>
        /// <param name="input_ImgUrl">要处理图片路径</param>
        /// <param name="out_ImgUrl">处理完毕图片路径</param>
        public void ImgReduceCutOut(int startX, int startY, int int_Width, int int_Height, string input_ImgUrl, string out_ImgUrl)
        {
            // ＝＝＝上传标准图大小＝＝＝
            int int_Standard_Width = 120;
            int int_Standard_Height = 120;

            int Reduce_Width = 0; // 缩小的宽度
            int Reduce_Height = 0; // 缩小的高度
            int CutOut_Width = 0; // 裁剪的宽度
            int CutOut_Height = 0; // 裁剪的高度
            int level = 100; //缩略图的质量 1-100的范围

            // ＝＝＝获得缩小，裁剪大小＝＝＝
            if (int_Standard_Height * int_Width / int_Standard_Width > int_Height)
            {
                Reduce_Width = int_Width;
                Reduce_Height = int_Standard_Height * int_Width / int_Standard_Width;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }
            else if (int_Standard_Height * int_Width / int_Standard_Width < int_Height)
            {
                Reduce_Width = int_Standard_Width * int_Height / int_Standard_Height;
                Reduce_Height = int_Height;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }
            else
            {
                Reduce_Width = int_Width;
                Reduce_Height = int_Height;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }

            // ＝＝＝通过连接创建Image对象＝＝＝
            int c = input_ImgUrl.IndexOf("?"); //取出？号的字符
            if (c > 0)
            {

            }
            else
            {
                c = input_ImgUrl.Length;
            }
            input_ImgUrl = input_ImgUrl.Substring(0, c); //去除随机数
            System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
            oldimage.Save(Server.MapPath("~/Update/temp.jpg"));
            oldimage.Dispose();

            //// ＝＝＝缩小图片＝＝＝
            //System.Drawing.Image thumbnailImage = oldimage.GetThumbnailImage(Reduce_Width, Reduce_Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            Bitmap bm = new Bitmap(Server.MapPath("~/Update/temp.jpg"));

            // ＝＝＝处理JPG质量的函数＝＝＝
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }
            }
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)level);

            // ＝＝＝裁剪图片＝＝＝
            Rectangle cloneRect = new Rectangle(startX, startY, CutOut_Width, CutOut_Height);
            PixelFormat format = bm.PixelFormat;
            Bitmap cloneBitmap = bm.Clone(cloneRect, format);

            // ＝＝＝保存图片＝＝＝
            c = out_ImgUrl.IndexOf("?"); //取出？号的字符
            if (c > 0)
            { }
            else
            {
                c = out_ImgUrl.Length;
            }
            out_ImgUrl = out_ImgUrl.Substring(0, c); //去除随机数
            cloneBitmap.Save(out_ImgUrl, ici, ep);
            bm.Dispose();
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// 获取没有目录和网址参数的文件名，如：http://www.sohu.com/123.jpg?time=123456获取后为123.jpg
        /// </summary>
        /// <param name="fileName"></param>
        private string GetFileTrueName(string fileName)
        {
            //剔除文件目录名等
            int j = fileName.LastIndexOf("/");
            if (j != -1)
            {
                fileName = fileName.Substring(j + 1, fileName.Length - j - 1);
            }

            //剔除随机数
            j = fileName.LastIndexOf("?");
            if (j != -1)
            {
                fileName = fileName.Substring(0, j);
            }
            return fileName;
        }



        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="isReturnPeriod">返回.号不</param>
        /// <returns></returns>
        private string GetExtensionName(string filename, bool isReturnPeriod)
        {
            int i = filename.IndexOf(".");
            string ext = string.Empty;
            //如果找到了并且不是最后一个字符
            if (i > 0 && i < filename.Length)
            {
                ext = filename.Substring(i + 1);
            }
            if (string.IsNullOrEmpty(ext))
            {
                return string.Empty;
            }
            if (isReturnPeriod)
            {
                return "." + ext;
            }
            else
            {
                return ext;
            }
        }
    }
}